package com.alm.token;

import android.app.Application;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.support.multidex.MultiDex;
import android.text.TextUtils;

import com.alm.token.api.AddCookiesInterceptor;
import com.alm.token.api.ReceivedCookiesInterceptor;
import com.alm.token.apinew.LogInterceptor;
import com.alm.token.ui.data.bean.ChannelTypeData;
import com.alm.token.ui.data.bean.CoinDetailData;
import com.alm.token.ui.data.bean.CurrencyChangeIndexData;
import com.alm.token.ui.data.bean.DrawIndexData;
import com.alm.token.ui.data.bean.MyTeamData;
import com.alm.token.ui.data.bean.UserData;
import com.alm.token.ui.data.bean.UserListLHData;
import com.alm.token.ui.data.bean.UserWalletData;
import com.alm.token.utils.LogUtil;
import com.blankj.utilcode.util.CrashUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.Utils;
import com.cryptape.cita_wallet.service.http.EthRpcService;
import com.cryptape.cita_wallet.util.crypto.AESCrypt;
import com.cryptape.cita_wallet.util.crypto.WalletEntity;
import com.cryptape.cita_wallet.util.db.SharePrefUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.smtt.sdk.QbSdk;
import com.yzq.zxinglibrary.bean.ZxingConfig;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import baibeiwallet.model.DaoMaster;
import baibeiwallet.model.DaoSession;
import baibeiwallet.model.MySQLiteOpenHelper;
import okhttp3.Cookie;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

//import com.uuzuche.lib_zxing.activity.ZXingLibrary;

/**
 * Created by en on 2018/12/28.
 */

public class MyApp extends Application {
    public static String key = "tmdshuijieshuishabi";
    private static String Content_Type = "application/x-www-form-urlencoded";
    public static Context context;

    public static UserData userData;
    public static String userName = "";
    public static String mail = "";
    public static MyTeamData.DataBean myTeamDataBean;

    public static CurrencyChangeIndexData.DataBean CurrencyChangeIndexDataBean;


    public static ChannelTypeData.DataBean channelTypeDataBean;

    public static DrawIndexData.DataBean drawIndexDataBean;

    public static boolean canTanchuang = true, needUpdaate = true;

    public static List<UserListLHData.DataBean> dataBeansGuanbi = new ArrayList<>();
    public static List<UserWalletData.DataBean.WalletsBean> wallets = new ArrayList<>();

    public static List<CoinDetailData.DataBean> coinDetailDataBean = new ArrayList<>();

    public static String Token = "";

    public static String updateApkUrl = "";
    public static Map<String, String> bizhongAdressMap;
    List<Cookie> cookies;

    public static MyApp myApp;
    public static final int TIMEOUT = 60;
    public static OkHttpClient mOkHttpClient;
    public static Application sInstance;
    public static ZxingConfig config;
    private DaoSession daoSession;

    public DaoSession getDaoSession() {
        return daoSession;
    }

    public static MyApp getsInstance() {
        return myApp;
    }

    public String MIDCode;

    //static 代码段可以防止内存泄露
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);//全局设置主题颜色
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        myApp = this;
        sInstance = this; //初始化工具库

        Context context = getApplicationContext();
        // 获取当前包名
        String packageName = context.getPackageName();
        // 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
        // 初始化Bugly
        CrashReport.initCrashReport(context, "0453e4b2d7", ConStant.ISDEBUG, strategy);
        Utils.init(this);
        LogUtils.dTag("CrashUtils==", "CrashUtils = " + getSDPath().getAbsolutePath());
        CrashUtils.init(getSDPath());
        initGreenDao();

        //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。
        QbSdk.PreInitCallback callback = new QbSdk.PreInitCallback() {
            @Override
            public void onViewInitFinished(boolean arg) {
                //x5內核初始化完成的回调，
                // true表示x5内核加载成功，
                // false表示x5内核加载失败，会自动切换到系统内核。
                LogUtil.e("QbSdk.Init=" + " x5内核加载  " + arg);
            }

            @Override
            public void onCoreInitFinished() {
            }
        };

        QbSdk.initX5Environment(getApplicationContext(), callback);

//        instance = this;
//        ZXingLibrary.initDisplayOpinion(this);
        WalletEntity.initWalletMnemonic(this);
        SharePrefUtil.init(this);
        EthRpcService.init(this);
        AESCrypt.init(this);
//        MultiLanguageUtil.init(this);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public List<Cookie> getCookies() {
        return cookies;
    }

    public void setCookies(List<Cookie> cookies) {
        this.cookies = cookies;
    }

    private void initGreenDao() {
        //创建数据库表
//        DaoMaster.DevOpenHelper mHelper = new DaoMaster.DevOpenHelper(this, "wallet", null);
//        MigrationHelper.DEBUG = true; //如果你想查看日志信息，请将DEBUG设置为true
        MySQLiteOpenHelper mHelper = new MySQLiteOpenHelper(this, "wallet",
                null);
        SQLiteDatabase db = mHelper.getWritableDatabase();
        daoSession = new DaoMaster(db).newSession();

//        //MigrationHelper.DEBUG = true; //如果你想查看日志信息，请将DEBUG设置为true
//        MySQLiteOpenHelper helper = new MySQLiteOpenHelper(this, "test.db",
//                null);
//        daoMaster = new DaoMaster(helper.getWritableDatabase());
    }

    /*ZxingConfig是配置类
     *可以设置是否显示底部布局，闪光灯，相册，
     * 是否播放提示音  震动
     * 设置扫描框颜色等
     * 也可以不传这个参数
     * */
    public static ZxingConfig getZxingConfig() {

        if (config == null) {
            config = new ZxingConfig();
            config.setPlayBeep(true);//是否播放扫描声音 默认为true
            config.setShake(true);//是否震动  默认为true
            config.setDecodeBarCode(true);//是否扫描条形码 默认为true
            config.setReactColor(R.color.colorAccent);//设置扫描框四个角的颜色 默认为白色
            config.setFrameLineColor(R.color.colorAccent);//设置扫描框边框颜色 默认无色
            config.setScanLineColor(R.color.colorAccent);//设置扫描线的颜色 默认白色
            config.setFullScreenScan(false);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
            config.setShowbottomLayout(true);//显示底部布局
            config.setShowAlbum(true);//闪光灯
            config.setShowFlashLight(true);//相册
        }
        return config;
    }

    /**
     * 全局httpclient
     *
     * @return
     */
    public static OkHttpClient initOKHttp() {
        if (mOkHttpClient == null) {
            // Log信息拦截器
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            //设置 Debug Log 模式

            mOkHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间
                    .readTimeout(TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
                    .writeTimeout(TIMEOUT, TimeUnit.SECONDS)//设置写入超时时间
                    .addInterceptor(loggingInterceptor)//添加日志拦截器
                    //cookie
                    .addInterceptor(new LogInterceptor()
                    )
                    .addInterceptor(new AddCookiesInterceptor()) //这部分
                    .addInterceptor(new ReceivedCookiesInterceptor()) //这部分
                    .build();
        }
        return mOkHttpClient;
    }

    public static void setToken(String token) {
        Token = token;
    }

    public static MyTeamData.DataBean getMyTeamDataBean() {
        return myTeamDataBean;
    }

    public static void setMyTeamDataBean(MyTeamData.DataBean myTeamDataBean) {
        MyApp.myTeamDataBean = myTeamDataBean;
    }

    public static String getUpdateApkUrl() {
        return updateApkUrl;
    }

    public static void setUpdateApkUrl(String updateApkUrl) {
        MyApp.updateApkUrl = updateApkUrl;
    }

    public static String getMail() {
        return mail;
    }

    public static void setMail(String mail) {
        MyApp.mail = mail;
    }

    public static UserData getUserData() {
        return userData;
    }

    public static void setUserData(UserData userData) {
        MyApp.userData = userData;
    }

    public static ChannelTypeData.DataBean getChannelTypeDataBean() {
        return channelTypeDataBean;
    }

    public static void setChannelTypeDataBean(ChannelTypeData.DataBean channelTypeDataBean) {
        MyApp.channelTypeDataBean = channelTypeDataBean;
    }

    public static List<UserListLHData.DataBean> getDataBeansGuanbi() {
        return dataBeansGuanbi;
    }

    public static void setDataBeansGuanbi(List<UserListLHData.DataBean> dataBeansGuanbi) {
        MyApp.dataBeansGuanbi = dataBeansGuanbi;
    }

    public static DrawIndexData.DataBean getDrawIndexDataBean() {
        return drawIndexDataBean;
    }

    public static void setDrawIndexDataBean(DrawIndexData.DataBean drawIndexDataBean) {
        MyApp.drawIndexDataBean = drawIndexDataBean;
    }

    public static CurrencyChangeIndexData.DataBean getCurrencyChangeIndexDataBean() {
        return CurrencyChangeIndexDataBean;
    }

    public static void setCurrencyChangeIndexDataBean(CurrencyChangeIndexData.DataBean currencyChangeIndexDataBean) {
        CurrencyChangeIndexDataBean = currencyChangeIndexDataBean;
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 获取sd卡路径
     *
     * @return
     */
    private File getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            // 这里可以修改为你的路径
            sdDir = new File(Environment.getExternalStorageDirectory() + ConStant.mFilePath);
            if (!sdDir.exists()) {
                sdDir.mkdirs();
            }
        }
        return sdDir;
    }
}
